﻿
using FluentFTP;
using System;
using System.Net;
using System.Text;

namespace KCommon
{
    public class PostToFTP
    {

        public PostToFTP(string ip, int port, string path, string username, string psw)
        {
            _IP = ip;
            _Port = port;
            _Path = path;
            _ID = username;
            _Password = psw;
        }
        private string _strMessage = "";
        public string Message
        {
            get
            {
                return _strMessage;
            }
        }

        private string _IP = "";
        private int _Port = 21;
        private string _Path = "";
        private string _ID = "";
        private string _Password = "";

        public bool ConnectToFTPServer()
        {
            bool isOK = false;
            using (FtpClient conn = new FtpClient())
            {
                conn.Host = _IP;
                conn.Port = _Port;
                conn.Credentials = new NetworkCredential(_ID, _Password);
                try
                {
                    conn.Connect();
                    //LogDB.Action.Add("FTP服务器连接成功.");
                    isOK = true;
                }
                catch (TimeoutException ex)
                {
                    _strMessage = "连接FTP服务器超时!\n请检查主机Host等配置是否正确。";
                    //LogDB.Error.Add(0x01020011, _strMessage);
                    isOK = false;
                }
                catch(Exception ex)
                {
                    _strMessage =string.Format("连接FTP服务器失败.\n详情:{0}", ex.Message);
                    //LogDB.Error.Add(0x01020011, _strMessage);
                    isOK = false;
                }
            }
            return isOK;
        }

        public string GetRemotePath()
        {
            StringBuilder builder = new StringBuilder();
            builder.Append("/");
            if (!string.IsNullOrEmpty(_Path))
            {
                builder.Append(_Path);
                builder.Append("/");
            }
            
            return builder.ToString();
        }

        public bool CreatRemotePath(string remoteDirection)
        {
            if(remoteDirection.Length == 0 || remoteDirection.Length == 1)
            {
                return true;
            }
            bool bRet = true;
            string direction = remoteDirection;
            if (remoteDirection[remoteDirection.Length - 1] == '/')
            {
                direction = remoteDirection.Remove(remoteDirection.Length - 1);
            }
            using (FtpClient conn = new FtpClient())
            {
                conn.Host = _Path;
                conn.Port = _Port;
                conn.Credentials = new NetworkCredential(_ID, _Password);
                if (!conn.DirectoryExists(direction))
                {
                    _strMessage = "";
                    try
                    {
                        conn.CreateDirectory(direction, true);
                        string strLog = string.Format("创建目录ftp:/{0}{1}成功!", _IP, direction);
                        //LogDB.Action.Add(strLog);
                    }
                    catch (Exception ex)
                    {
                        _strMessage = string.Format("创建目录ftp:/{0}{1}失败! \n异常详情:{2}\n{3}",
                            _IP,
                            direction,
                            ex.Message,
                            ex.InnerException);
                        //LogDB.Error.Add(0x01020011, _strMessage);
                        bRet = false;
                    }                    
                }
            }
            return bRet;
        }

        public bool UploadFile(string localFile)
        {
            string fileName = System.IO.Path.GetFileName(localFile);
            string remoteFile = _Path + fileName;
            bool isOK = false;
            using (FtpClient conn = new FtpClient())
            {
                conn.Host = _IP;
                conn.Port = _Port;
                conn.Credentials = new NetworkCredential(_ID, _Password);
                try
                {
                    conn.UploadFile(
                        localFile,
                        remoteFile,
                        FtpExists.Overwrite,
                        true,
                        FtpVerify.Retry);
                   
                    string strLog = string.Format("本地文件{0}上传至ftp:/{1}{2}成功!", localFile, _IP, remoteFile);
                    //string newName = _Path + Path.GetFileNameWithoutExtension(fileName)+".zip";
                    //conn.Rename(remoteFile, newName);
                    //LogDB.Action.Add(strLog);
                    conn.Disconnect();
                    isOK = true;
                }
                catch (TimeoutException ex)
                {
                    _strMessage = "连接FTP服务器超时!\n请检查主机Host等配置是否正确。";
                    //LogDB.Error.Add(0x01020011, _strMessage);
                    isOK = false;
                }
                catch (Exception ex)
                {
                    _strMessage = string.Format("上传文件至ftp:/{0}{1}失败! \n异常详情:{2}\n{3}",
                        _IP,
                        remoteFile,
                        ex.Message,
                        ex.InnerException);
                    //LogDB.Error.Add(0x01020011, _strMessage);
                    isOK = false;
                }        
            }
            return isOK;
        }
    }
}
